<template>
  <el-container style="height: 100vh">
    <Aside/>
    <el-container>
      <el-main style="border-right: 1px solid transparent; border-image: linear-gradient(to bottom, #e0c3fc, #8ec5fc) 1 100%;">
        <!--主页面-->
        <h1 class="title" style="color: black">User Management</h1>
        <br>
        <el-input
            v-model="searchQuery"
            placeholder="请输入搜索内容"
            style="margin-bottom: 20px; width: 300px;"
        >
          <template #prepend>
            <el-icon>
              <search />
            </el-icon>
          </template>
        </el-input>
        <el-table
            :data="filteredTableData"
            style="width: 100%; border-radius: 10px"
            max-height="400">
          <el-table-column
              fixed
              prop="Id"
              label="Id"
              width="150">
          </el-table-column>
          <el-table-column
              fixed
              prop="Name"
              label="姓名"
              width="120">
          </el-table-column>
          <el-table-column
              fixed
              prop="Avatar"
              label="头像"
              width="120">
            <template #default="{ row }">
              <img :src="avatarFormatter(row.Avatar)" alt="Avatar" style="width: 50px; height: 50px; border-radius: 50%;" />
            </template>
          </el-table-column>
          <el-table-column
              prop="Email"
              label="邮箱"
              width="200">
          </el-table-column>
          <el-table-column
              prop="CreateTime"
              label="注册时间"
              width="250">
          </el-table-column>
          <el-table-column
              prop="Role"
              label="权限"
              width="120"
              :formatter="roleFormatter">
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="120">
            <template #default="{ row, $index }">
              <el-button
                  @click="confirmDeleteRow($index, row.Id)"
                  type="text"
                  size="small">
                移除
              </el-button>
              <br>
              <el-button
                  @click="drawer2 = true; editUserId = row.Id"
                  type="text"
                  size="small">
                更改
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 抽屉内容 -->
        <el-drawer v-model="drawer2" :direction="direction">
          <template #header>
            <h4>编辑</h4>
          </template>
          <el-form label-width="auto">
            <el-form-item label="修改名字:" >
              <el-input v-model="input" placeholder="请输入内容"></el-input>
            </el-form-item>
            <br>
            <hr>
            <br>
            <el-form-item style="margin-left: 10%">
              <el-button @click="changeRole('up', editUserId)">权限升级</el-button>
              <el-button @click="changeRole('down', editUserId)">权限降级</el-button>
            </el-form-item>
            <br>
            <hr>
            <br>
            <el-form-item style="margin-left: 10%">
              <el-button @click="rsAvatar(editUserId)">头像重置</el-button>
            </el-form-item>
          </el-form>
          <template #footer>
            <div style="flex: auto">
              <el-button @click="cancelClick">取消</el-button>
              <el-button type="primary" @click="confirmClick">确认</el-button>
            </div>
          </template>
        </el-drawer>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import Aside from '@/components/aside.vue';
import {deleteUser, getUserList, updateUser, updateUserRole} from '@/api/user';
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';

// 搜索框
const searchQuery = ref('');
const tableData = ref([]);

// 抽屉参数
const drawer2 = ref(false);
const direction = ref('rtl');
const input = ref('');
const editUserId = ref('');

// 用户权限
let roleValue

// 搜索过滤
const filteredTableData = computed(() => {
  if (!searchQuery.value) {
    return tableData.value;
  }
  const query = searchQuery.value.toLowerCase();
  return tableData.value.filter(row =>
      Object.values(row).some(value =>
          String(value).toLowerCase().includes(query)
      )
  );
});

const fetchData = async () => {
  try {
    const response = await getUserList();
    if (response.code === 200) {
      tableData.value = response.data;
    }
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
}

onMounted(() => {
  fetchData();
});

const changeRole = async (action, userId) => {
  // console.log('未改变前的权限：'+roleValue)
  try {
    if (action === "up") {
      roleValue = 1;
    } else if (action === "down") {
      roleValue = 0;
    }
    const userData = {
      role: roleValue
    };
    // console.log("修改后的权限：" + userData.role)
    const response = await updateUserRole(userId, userData);

    if (response.code === 200) {
      ElMessage({
        type: 'success',
        message: roleValue === 1
            ? '权限升级成功，该用户现为管理员'
            : '权限降级成功，该用户现为普通用户'
      });
      await fetchData();
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '修改权限失败'
    });
    console.error("Failed to change role:", error);
  }
};

const rsAvatar = async (userId) => {
  try {
    const avatar = "defaultAvatar.jpg";
    const userData = {
      avatar: avatar,
    };
    const response = await updateUser(userId, userData);
    if (response.code === 200) {
      ElMessage({
        type: 'success',
        message: '头像重置成功'
      });
      await fetchData();
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '头像重置失败'
    });
    console.error("Failed to reset avatar:", error);
  }
}

const avatarFormatter = (value) => {
  return `http://localhost:8081/img/${value}`;
};

const roleFormatter = (row, column, value) => {
  return value === 1 ? '管理员' : '普通用户';
};

const deleteRow = async (index, id) => {
  try {
    const response = await deleteUser(id);
    if (response.code === 200) {
      tableData.value.splice(index, 1);
      ElMessage({
        type: 'success',
        message: '删除成功'
      });
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '删除失败'
    });
    console.error("Failed to delete user:", error);
  }
};

function cancelClick() {
  drawer2.value = false;
}

const confirmClick = () => {
  ElMessageBox.confirm('确认提交修改吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        const userData = {
          name: input.value,
        };

        try {
          const response = await updateUser(editUserId.value, userData);
          if (response.code === 200) {
            ElNotification({
              title: '成功',
              message: '修改名字成功',
              type: 'success',
            });
            await fetchData(); // 重新获取用户信息
          }
        } catch (error) {
          console.error('Failed to update user:', error);
          ElNotification({
            title: '失败',
            message: '修改名字失败',
            type: 'error',
          });
        }

        drawer2.value = false;
      })
      .catch(() => {
        ElNotification({
          title: '取消',
          message: '操作已取消',
          type: 'warning',
        });
      });
};

const confirmDeleteRow = (index, id) => {
  ElMessageBox.confirm('你确定要删除这个用户吗？', '确认信息', {
    distinguishCancelAndClose: true,
    confirmButtonText: '删除',
    cancelButtonText: '取消'
  })
      .then(() => {
        deleteRow(index, id);
      })
      .catch(action => {
        ElMessage({
          type: 'info',
          message: action === 'cancel'
              ? '取消删除'
              : '操作被关闭'
        });
      });
};
</script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Pacifico&display=swap');

html, body {
  height: 100%;
  margin: 0;
}

.main-content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;
  height: 100%;
  padding: 20px; /* 添加内边距以避免靠得太紧 */
}

.right-container {
  flex: 1;
  margin-left: 20px; /* 确保间距一致 */
}

.text-content {
  flex: 1;
  color: black;
  font-weight: 400;
  font-style: normal;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.content {
  font-size: 18px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.19);
  margin: 20px;
  font-family: Arial, sans-serif;
  background: linear-gradient(to right, #8ec5fc, #e0c3fc);
}

.title {
  font-size: 50px;
  text-align: center;
  font-family: "Pacifico", cursive;
}

// 容器样式
.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  line-height: 160px;
}

.el-header {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
  line-height: 60px;
  border-radius: 10px;
}

.el-container {
  background: linear-gradient(to right, #e0c3fc, #8ec5fc);
  height: 100%;
}
</style>
